package hu.rsc.forbiddenwords.client.gui.entry;

import hu.rsc.forbiddenwords.client.Forbiddenwords;
import hu.rsc.forbiddenwords.client.util.Logger;
import hu.rsc.forbiddenwords.client.util.SimpleCallback;
import hu.rsc.forbiddenwords.shared.EntryDTO;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasVerticalAlignment;

public class EntryPanel extends Composite {
    private EntryTable table;
    private EntryForm form;

    public EntryPanel() {
	FlexTable main = new FlexTable();
	main.addStyleName("gwt-InlineCellEditor");
	this.table = new EntryTable(this);
	main.setWidget(0, 0, this.form = new EntryForm(this));
	main.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
	main.setWidget(0, 1, this.table);
	initWidget(main);
    }

    public EntryDTO getEntry() {
	return this.form.getEntry();
    }

    public Long getEntryId() {
	return getEntry().getId();
    }

    public void refresh(EntryDTO entry) {
	refreshFeedsTable();
	refreshForm(entry);
    }

    public void refreshFeedsTable() {
	this.table.refreshTable();
    }

    public void refreshForm(EntryDTO entry) {
	this.form.refresh(entry);
    }

    public void save(EntryDTO entry) {
	Forbiddenwords.getService().saveEntry(entry, new SimpleCallback<EntryDTO>() {

	    @Override
	    public void onSuccess(EntryDTO result) {
		if (result == null) {
		    Logger.logError("You are not the application owner");
		}
		EntryPanel.this.table.refreshTable();
		EntryPanel.this.form.refresh(result);
	    }
	});
    }

}
